package com.yango.smsservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.yango.smsservice.service.SmsService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @author Li.Ding.yin
 * @create 2021年07月30日19:56-星期五
 * @role 短信服务业务层实现类
 */
@Service
public class SmsServiceImpl implements SmsService {

    //根据手机号发送短信验证码
    @Override
    public boolean sendCode(String phone, String templateCode, Map<String, Object> param) {
        //如果手机号为空，返回false
        if (StringUtils.isEmpty(phone)) {
            return false;
        }
        //构建参数,
        /**
         * 三个参数：
         * 第一个：默认参数：default
         * 第二个：签名id
         * 第三个：秘钥
         */
        DefaultProfile profile =
                DefaultProfile.getProfile(
                        "default",
                        "LTAIq6nIPY09VROj",
                        "FQ7UcixT9wEqMv9F35nORPqKr8XkTF");
        //创建client对象
        DefaultAcsClient client = new DefaultAcsClient(profile);
        //设置固定参数
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        //设置发送参数
        request.putQueryParameter("PhoneNumbers", phone);//接收短信手机号
        request.putQueryParameter("SignName", "阳光学院Java在线学习平台");
        request.putQueryParameter("TemplateCode", templateCode);//验证码
        //map集合中的数据转换成json数据
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));
        try {
            //调用方法获取响应
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            //返回状态
            return response.getHttpResponse().isSuccess();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
